package com.saas.ability.core.base.view;


import com.saas.ability.core.base.config.AliyunossProperties;
import com.saas.ability.core.base.util.DateUtil;
import com.saas.ability.core.base.util.UploadUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.document.AbstractXlsxView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * Excel工具类
 */

@Component
public class ObjectExcelView extends AbstractXlsxView {


    @Autowired
    private UploadUtil uploadUtil;


    @Autowired
    AliyunossProperties aliyunossProperties;

    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Date date = new Date();
        String filename = DateUtil.date2Str(date, "yyyyMMddHHmmss");
        // change the file name
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xlsx");
        // create excel xls sheet
        Sheet sheet = workbook.createSheet("Sheet1");
        // 设置标题
        List<String> titles = (List<String>) model.get("titles");
        int len = titles.size();
        Row header = sheet.createRow(0);
        for (int i = 0; i < len; i++) {
            String title = titles.get(i);
            header.createCell(i).setCellValue(title);
        }
        // Create data cells
        int rowCount = 1;
        List varList =  (List) model.get("varList");
        int varCount = varList.size();
        for (int i = 0; i < varCount; i++) {
            Map vpd = (Map) varList.get(i);
            Row courseRow = sheet.createRow(rowCount++);
            for (int j = 0; j < len; j++) {
                Object varstr = vpd.get("var" + (j + 1)) != null ? vpd.get("var" + (j + 1)) : "";
                if(null != varstr && varstr instanceof BigDecimal){
                    BigDecimal temp = (BigDecimal) varstr;
                    courseRow.createCell(j).setCellValue(temp.doubleValue());
                }else if(null != varstr && varstr instanceof Integer){
                    courseRow.createCell(j).setCellValue((Integer)varstr);
                }else{
                    courseRow.createCell(j).setCellValue(varstr.toString());
                }
            }

            if(i % 1000 == 0){
                Thread.sleep(500);
            }
        }


    }

    /**
     * 生成Excel文件
     * @param titles
     * @param list LinkedHashMap 按title顺序进行数据组装
     * @param path 文件存放位置
     * @return
     * @throws IOException
     */
    public String createExcel(List<String> titles,List<Map<String,String>> list,String path) throws Exception {
        int rowAccess = 1000;
        SXSSFWorkbook wb = new SXSSFWorkbook();
        Sheet sheet = wb.createSheet();
        //设置标题
        Row row = sheet.createRow(0);
        for(int i = 0; i < titles.size(); i++){
            row.createCell(i).setCellValue(titles.get(i));
        }
        //填充数据
        int rowCount = 1;
        for(int i = 0; i < list.size(); i++){
            row = sheet.createRow(rowCount++);
            int j = 0;
            for(Object obj:list.get(i).values()){
                if(null != obj && obj instanceof BigDecimal){
                    row.createCell(j++).setCellValue(((BigDecimal) obj).doubleValue());
                }else if(null != obj && obj instanceof Integer){
                    row.createCell(j++).setCellValue((Integer) obj);
                }else{
                    row.createCell(j++).setCellValue(obj != null ? obj.toString():"");
                }
            }
            if(i%rowAccess==0){
                ((SXSSFSheet)sheet).flushRows();
            }
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        byte[] b = os.toByteArray();
        os.close();

        ByteArrayInputStream in = new ByteArrayInputStream(b);
        uploadUtil.putObject(path, in);
        in.close();
        return aliyunossProperties.getMappoint1() + path;
    }

}